package com.jcf.springboot;

import com.jcf.springboot.entity.business.Member;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Date;

/**
 * @author ${chaofan.ji}
 * @since 2025/4/11
 */
@Component

public class MailReceiver {
  @Autowired
  private JavaMailSender javaMailSender;
  @Autowired
  private MailProperties mailProperties;
  @Autowired
  private TemplateEngine templateEngine;
  @RabbitListener(queues="mail.welcome")
  public void handleer(Member member) throws MessagingException {
    MimeMessage msg = javaMailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(msg);
    helper.setFrom(mailProperties.getUsername());
    helper.setTo(member.getMemberEmail());
    helper.setSubject("欢迎邮件");
    helper.setSentDate(new Date());
    Context context = new Context();
    context.setVariable("name",member.getMemberName());
    String mail = templateEngine.process("mail", context);
    helper.setText(mail);
    javaMailSender.send(msg);
  }

}
